from openpyxl import Workbook
from openpyxl.chart import (
    ScatterChart,  # 散点图
    Reference,
    Series,
)

# 工作表
wb = Workbook()
ws = wb.active

# 准备数据
rows = [
    ['Size', 'Batch 1', 'Batch 2'],
    [2, 40, 30],
    [3, 40, 25],
    [4, 50, 30],
    [5, 30, 25],
    [6, 25, 35],
    [7, 20, 40],
]

# 向工作表中追加数据
for row in rows:
    ws.append(row)

# 创建散点图
chart = ScatterChart()
chart.title = "散点图"
chart.style = 13
chart.x_axis.title = 'x轴'
chart.y_axis.title = 'y轴'

# x轴数据
xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)

# 循环追加系列
values = Reference(ws, min_col=2, min_row=1, max_row=7)
series = Series(values, xvalues, title_from_data=True)
chart.series.append(series)

# 将图表插入到工作表指定位置
ws.add_chart(chart, "A10")
# 保存散点图
wb.save("scatter.xlsx")
